package com.suneast.suneaststore.modules.shopcart;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.bean.goodsdetail.ItemShopCart2UpLoading;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.modules.personal.address.AddressListFragment;
import com.suneast.suneaststore.modules.shopcart.adapter.BillAdapter;
import com.suneast.suneaststore.bean.shopcart.ShopGoodsListBean;
import com.suneast.suneaststore.bean.shopcart.SubmitBillBean;
import com.suneast.suneaststore.modules.shopcart.event.GotBillInfo;
import com.suneast.suneaststore.modules.shopcart.event.SubmitBillResult;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class BillConfirmFragment extends BaseFragment {

    private int type = 1;

    public BillConfirmFragment withType(int type) {
        this.type = type;
        return this;
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_confirm_bill;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initData();
        initView();
        if (type == 1) {//从购物车跳转过来的
            submitBillBean.setFromCart(1);
            ShopCartHandler.requestBill();
        } else {
            submitBillBean.setFromCart(2);
            Bundle bundle = getArguments();
            if (bundle != null) {
                ItemShopCart2UpLoading itemShopCart = bundle.getParcelable("item");
                if (itemShopCart != null) {
                    ShopCartHandler.requestBill(itemShopCart);
                } else {
                    Log.e(TAG, "onBindView: item null");
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    SubmitBillBean submitBillBean = null;
    ArrayList<ShopGoodsListBean> selectedShopCartList = null;

    private void initData() {
        submitBillBean = new SubmitBillBean();
        selectedShopCartList = new ArrayList<>();
    }

    @BindView(R.id.toolbar_pay)
    public Toolbar payToolbar;
    @BindView(R.id.tv_consignee_and_phone_number)
    public TextView consigneeTv;
    @BindView(R.id.tv_address)
    public TextView addressTv;
    @BindView(R.id.rv_goods_list)
    public RecyclerView goodsListRV;
    BillAdapter adapter;

    @BindView(R.id.tv_discount)
    public TextView discountTv;
    @BindView(R.id.tv_deliver_price)
    public TextView deliverPriceTv;
    @BindView(R.id.rg_invoice_type)
    public RadioGroup invoiceTypeRG;
    @BindView(R.id.et_billing_info)
    public EditText billingInfoEt;
    @BindView(R.id.et_illustration)
    public EditText illustrationEt;
    @BindView(R.id.tv_total_pay)
    public TextView totalPayTv;
    @BindView(R.id.tv_real_pay)
    public TextView realPayTv;

    private void initView() {
        payToolbar.setNavigationOnClickListener((View v) -> {
            pop();
        });
        goodsListRV.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new BillAdapter(R.layout.item_shopping_cart);
        goodsListRV.setAdapter(adapter);
        invoiceTypeRG.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
            submitBillBean.setInvoiceType(checkedId == R.id.rb_enterprice ? 2 : 1);
        });
        billingInfoEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                submitBillBean.setInvoiceInfo(s.toString());
            }
        });
        illustrationEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                submitBillBean.setRemark(s.toString());
            }
        });
    }

    private double suitableCoin = 0.00;

    private void setView(GotBillInfo info) {
        AddressBean addressBean = info.getAddressBean();
        consigneeTv.setText(addressBean.getRealname() + " " + addressBean.getMobile());
        addressTv.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea()
                + addressBean.getTown() + addressBean.getAddress());
        adapter.setNewData(info.getShopGoodsListBeanList());
        double totalCoin = Double.valueOf(info.getMember().getCredit1());
        suitableCoin = Math.min(totalCoin, info.getCoinPrice());
        discountTv.setText(String.format(getResources().getString(R.string.discount_info),
                String.format("%.2f", suitableCoin),
                String.format("%.2f", suitableCoin)));
        setTotalPriceText(info.getTotalCount(), info.getTotalPrice(),
                info.getRealPrice(), info.getCoinRewardPrice());
    }

    @OnClick({R.id.layout_address, R.id.btn_pay_it_now})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.layout_address: {
                AddressListFragment fragment = new AddressListFragment();
                Bundle bundle = new Bundle();
                bundle.putInt(AddressListFragment.KEY_TYPE, 1);
                fragment.setArguments(bundle);
                startForResult(fragment, 3);
            }
            break;
            case R.id.btn_pay_it_now: {
                ShopCartHandler.submitBill(submitBillBean);
            }
            break;
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 3: {
                if (resultCode == RESULT_OK) {
                    AddressBean addressBean = data.getParcelable("address_bean");
                    if (addressBean != null) {
                        if (submitBillBean != null) {
                            submitBillBean.setAddressId(addressBean.getId());
                        }
                        consigneeTv.setText(addressBean.getRealname() + " " + addressBean.getMobile());
                        addressTv.setText(addressBean.getProvince() + addressBean.getCity()
                                + addressBean.getArea() + addressBean.getAddress());
                    }
                }
            }
            break;
        }
    }

    GotBillInfo billInfo = null;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotBillInfo(GotBillInfo info) {
        billInfo = info;
        submitBillBean.setAddressId(info.getAddressBean().getId());
        submitBillBean.setGoodsListJsonStr(info.getCreateInfo());
        selectedShopCartList.addAll(info.getShopGoodsListBeanList());
        setView(info);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubmitBillResult(SubmitBillResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            startWithPop(new HandlePayFragment().withId(result.getOrderId()));
        } else {
            Toast.makeText(getContext(), "提交订单失败", Toast.LENGTH_SHORT).show();
        }
    }

    @OnCheckedChanged({R.id.cb_use_discount, R.id.cb_design, R.id.cb_home_measure})
    public void onCheckBoxCheckedChange(CompoundButton btn, boolean isChecked) {
        switch (btn.getId()) {
            case R.id.cb_use_discount: {
                submitBillBean.setUseLBCoin(isChecked ? 1 : 0);
                setTotalPriceText(billInfo.getTotalCount(), billInfo.getTotalPrice(),
                        submitBillBean.getUseLBCoin() == 0 ? billInfo.getRealPrice()
                                : billInfo.getRealPrice() - suitableCoin,
                        billInfo.getCoinRewardPrice());
            }
            break;
            case R.id.cb_design: {
                submitBillBean.setDesign(isChecked ? 1 : 0);

            }
            break;
            case R.id.cb_home_measure: {
                submitBillBean.setHomeMeasure(isChecked ? 1 : 0);

            }
            break;
        }
    }

    private void setTotalPriceText(int count, double totalPrice, double realPrice, int coinRewardValue) {
        totalPayTv.setText(String.format(getString(R.string.bill_confirm_total_price),
                String.valueOf(count), String.format("%.2f", totalPrice)));
        realPayTv.setText(String.format(getString(R.string.bill_confirm_real_pay_price),
                String.format("%.2f", realPrice), String.valueOf(coinRewardValue)));
        realPayTv.setText("实付" + String.format("%.2f", billInfo.getRealPrice()) + " 返帘邦豆"
                + billInfo.getCoinRewardPrice() + "个");
    }

}

